<template>
  <div>
    <div id="cesiumContainer" ref="viewerDivRef"></div>
    <div class="weather-wrapper" v-if="showweather">
      <weather></weather>
    </div>
    <div v-if="showswitchbox && activeMode == 1" class="toolBox"
      :style="{ right: (rightIsShow ? 339 + 'px' : 76 + 'px') }" style="top: 162px;height: 70px;width: 0;">
      <div class="toolbarDiv" @click="handleMark">
        <el-icon style="color: white;">
          <Flag />
        </el-icon>
      </div>
      <div class="toolbarDiv">
        <el-icon style="color: white;">
          <VideoPlay />
        </el-icon>
      </div>
    </div>
    <div class="switchBox" :style="{ right: (rightIsShow ? 339 + 'px' : 76 + 'px') }" v-if="showswitchbox && dockMan">
      <div class="switchDiv" :class="{ 'isActive': activeMode === 1 }" @click="setSceneMode(1)">2D</div>
      <div class="switchDiv" :class="{ 'isActive': activeMode === 2 }" @click="setSceneMode(2)">3D</div>
    </div>
    <div class="toolBox" :style="{ right: (rightIsShow ? 339 + 'px' : 76 + 'px') }" v-if="showtoolbox">
      <div class="toolbarDiv" @click="toggleSearch">
        <el-icon color="white">
          <Search />
        </el-icon>
        <div v-if="showSearch" class="search-container" @click.stop :style="{ right: (rightIsShow ? 40 + 'px' : 6) }">
          <el-autocomplete v-model="searchKeyword" :fetch-suggestions="querySearch" placeholder="请输入地址"
            @select="handleSelect" class="search-input" popper-class="my-autocomplete" :trigger-on-focus="true"
            clearable @clear="resetSearch">
            <template #default="{ item }">
              <div class="search-suggestion-item">
                <span>{{ item.name }}</span>
                <span class="district">{{ item.district }}</span>
              </div>
            </template>
          </el-autocomplete>
        </div>
      </div>
      <div class="toolbarDiv" @click="handleLocation"><el-icon color="white">
          <MapLocation />
        </el-icon></div>
      <div class="toolbarDiv" v-if="activeMode === 1" @click="handleMeasureDistance">
        <el-icon color="white">
          <Film />
        </el-icon>
        <!-- 新增测量模式选择框 -->
        <div class="measureModeBox" v-if="showMeasureBox" :style="{ left: (showMeasureBox ? '-40px' : '0px') }">
          <div class="modeItem" :class="{ active: isMeasureDistance }" @click="selectMeasureMode('distance')">
            测距
          </div>
          <div class="modeItem" :class="{ active: isMeasureArea }" @click="selectMeasureMode('area')">
            测面积
          </div>
        </div>
      </div>
      <div class="toolbarPm">
        <div class="toolbarDiv" @click="zoomIn"><el-icon color="white">
            <Plus />
          </el-icon></div>
        <div class="line"></div>
        <div class="toolbarDiv" @click="zoomOut"><el-icon color="white">
            <Minus />
          </el-icon></div>
      </div>
      <a class="toolLayer toolbarDiv" @click="toggleLayerSettings">
        <div class="LayerBox">
          <div class="LayerWrapper">
            <el-icon>
              <Files />
            </el-icon>
            <span>图层</span>
          </div>
        </div>
      </a>
    </div>
    <div class="markBox" v-if="dialogVisible" :style="{ right: (rightIsShow ? 339 + 'px' : 76 + 'px') }">
      <div style="display: flex;justify-content: space-evenly;width: 50%">
        <el-tooltip content="新建点" placement="bottom" effect="light">
          <div @click="handleIconClick('point')">
            <svg-icon icon-class="adian" />
          </div>
        </el-tooltip>
        <el-tooltip content="新建线" placement="bottom" effect="light">
          <div @click="handleIconClick('line')"><svg-icon icon-class="axian" /></div>
        </el-tooltip>
        <el-tooltip content="新建面" placement="bottom" effect="light">
          <div @click="handleIconClick('surface')"><svg-icon icon-class="amian" /></div>
        </el-tooltip>
      </div>
      <el-divider direction="vertical" />
      <div style="display: flex;justify-content: space-evenly;width: 50%">
        <el-tooltip content="隐藏标签" placement="bottom" effect="light">
          <div @click="showName"><svg-icon icon-class="previewclose" /></div>
        </el-tooltip>
        <el-tooltip content="隐藏图形" placement="bottom" effect="light">
          <div @click="showGraphic"><svg-icon icon-class="label" /></div>
        </el-tooltip>
        <el-tooltip content="删除所有任务" placement="bottom" effect="light">
          <div @click="deleteAllTasks"><svg-icon icon-class="delete" /></div>
        </el-tooltip>
      </div>
    </div>

    <!-- 新增的任务表单 -->
    <div class="taskForm" v-if="showTaskForm" :style="{ right: (rightIsShow ? 339 + 'px' : 76 + 'px') }">
      <div class="formHeader">{{ isEditMode ? '任务详情' : '新建任务' }}</div>
      <div class="formBody">
        <div class="formItem">
          <label>任务名称：</label>
          <el-input v-model="taskForm.name" size="small" :readonly="isEditMode"></el-input>
        </div>

        <!-- 点任务 -->
        <div v-if="currentTaskType === 'point'">
          <div class="formItem">
            <label>颜色：</label>
            <div v-if="isEditMode" class="colorDisplay" :style="{ backgroundColor: taskForm.color }"></div>
            <div v-else class="colorPicker">
              <div v-for="color in colors" :key="color" :style="{ backgroundColor: color }"
                @click="handleColorChange(color)" :class="{ selected: taskForm.color === color }"></div>
            </div>
          </div>
        </div>

        <!-- 线任务 -->
        <div v-if="currentTaskType === 'line'">
          <div class="formItem">
            <label>总长(公里)：</label>
            <el-input v-model="taskForm.length" size="small" readonly suffix-icon="公里"></el-input>
          </div>
          <div class="formItem">
            <label>颜色：</label>
            <div v-if="isEditMode" class="colorDisplay" :style="{ backgroundColor: taskForm.color }"></div>
            <div v-else class="colorPicker">
              <div v-for="color in colors" :key="color" :style="{ backgroundColor: color }"
                @click="handleColorChange(color)" :class="{ selected: taskForm.color === color }"></div>
            </div>
          </div>
        </div>

        <!-- 面任务 -->
        <div v-if="currentTaskType === 'surface'">
          <div class="formItem">
            <label>面积(平方公里)：</label>
            <el-input v-model="taskForm.area" size="small" readonly suffix-icon="平方公里"></el-input>
          </div>
          <div class="formItem">
            <label>颜色：</label>
            <div v-if="isEditMode" class="colorDisplay" :style="{ backgroundColor: taskForm.color }"></div>
            <div v-else class="colorPicker">
              <div v-for="color in colors" :key="color" :style="{ backgroundColor: color }"
                @click="handleColorChange(color)" :class="{ selected: taskForm.color === color }"></div>
            </div>
          </div>
        </div>
      </div>

      <div class="formFooter">
        <el-button @click="cancelTask">{{ isEditMode ? '关闭' : '取消' }}</el-button>
        <el-button v-if="!isEditMode" type="primary" @click="confirmTask">确定</el-button>
      </div>
    </div>
    <div class="bottomBox" v-if="showbottomBox">
      <div style="margin-top: 3px;">{{ longitude }}°E，{{ latitude }}°N</div>
    </div>
    <!-- 新增地图设置面板 -->
    <div class="layerSettings" v-if="showLayerSettings" :style="{ right: (rightIsShow ? 339 + 'px' : 150 + 'px') }">
      <div class="settingsHeader">地图设置</div>
      <el-divider />
      <div class="settingsSection">
        <div class="sectionTitle">亮度调节</div>
        <el-slider v-model="brightness" :min="0" :max="100" @change="handleBrightnessChange" />
      </div>
      <div v-if="activeMode === 2" class="settingsSection">
        <div class="sectionTitle">3D模型设置</div>
        <div class="modelSettings">
          <div class="modelOption" :class="{ active: modelQuality === 'high' }" @click="setModelQuality('high')">高清显示
          </div>
          <div class="modelOption" :class="{ active: modelQuality === 'low' }" @click="setModelQuality('low')">流畅显示
          </div>
        </div>
      </div>
      <div class="settingsSection">
        <div class="sectionTitle">地图类型</div>
        <div class="mapTypeContainer">
          <div class="mapTypeBox" :class="{ active: currentMapType === 'normal' }" @click="switchMapType('normal')">
            <div class="mapTypeImage normal"></div>
            <div class="mapTypeLabel">天地图普通</div>
          </div>
          <div class="mapTypeBox" :class="{ active: currentMapType === 'satellite' }"
            @click="switchMapType('satellite')">
            <div class="mapTypeImage satellite"></div>
            <div class="mapTypeLabel">天地图卫星</div>
          </div>
        </div>
      </div>
      <div class="settingsSection">
        <div class="sectionTitle">叠加图层</div>
        <div class="overlayContainer">
          <div class="overlayBox" :class="[{ active: roadNetworkVisible }]" @click="toggleRoadNetwork">
            <div class="overlayImage road"></div>
            <div class="overlayLabel">路网</div>
          </div>
          <div class="overlayBox" :class="[{ active: flightRestrictionActive }]" @click="toggleFlightRestriction">
            <div class="overlayImage flight"></div>
            <div class="overlayLabel">民航禁飞区</div>
          </div>
          <div class="overlayBox" :class="[{ active: systemRestrictionVisible }]" @click="toggleSystemRestriction">
            <div class="overlayImage system"></div>
            <div class="overlayLabel">系统禁飞区</div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { onMounted, ref, nextTick, defineProps, watch, defineEmits } from 'vue'
import {
  Cartesian3,
  Cartographic,
  Color, DirectionalLight,
  Ion,
  Math as CesiumMath,
  Rectangle,
  SceneMode,
  ScreenSpaceEventHandler,
  ScreenSpaceEventType,
  Terrain,
  UrlTemplateImageryProvider,
  Viewer,
  WebMercatorTilingScheme,
  JulianDate,
  ClockRange,
  TimeIntervalCollection,
  TimeInterval,
  SampledPositionProperty,
  VelocityOrientationProperty,
  PolylineGlowMaterialProperty,
  CallbackProperty,
  HeadingPitchRoll,
  Transforms,
  SampledProperty
} from 'cesium'
import 'cesium/Build/CesiumUnminified/Widgets/widgets.css'
import CesiumDrone from '@/assets/models/CesiumDrone.glb';
import useMapStore from '@/store/modules/map'
import { addPointTask, deleteAllTaskByIds, deletePointTaskById } from "@/api/drawtask/point/pointTask.js";
import { addLineTask, deleteLineTaskById } from "@/api/drawtask/line/lineTask.js";
import { addSurfaceTask, deleteSurfaceTaskById } from "@/api/drawtask/surface/surfaceTask.js";
import { getHxUnflyZoneList } from "@/api/unflyzone/hx/hxUnfly";
import { getDbxUnflyZoneList } from "@/api/unflyzone/dbx/dbxUnfly";
import { ElMessage, ElMessageBox, ElTooltip } from "element-plus";
import defaultNoFlyZone from '@/assets/resData/defaultNoFlyZone.json';
import CesiumDrawTool from '@/utils/CesiumDrawTool'; // 绘制工具类
import CesiumNavigation from 'cesium-navigation-es6'
import CesiumMeasureDistance from "@/utils/CesiumMeasureDistance"; //测距工具类
import CesiumMeasureArea from "@/utils/CesiumMeasureArea";//测面积工具类
import weather from '@/views/weather/weather';
const mapReady = ref(false)
const viewerDivRef = ref()
const activeMode = ref(1)
let viewer = null
const emit = defineEmits([
  'circle-update',
  'polygon-update',
  'draw-point',
  'draw-line',
  'draw-surface',
  'refresh',
  'entity-delete',
  'entity-hover',
  'data-point-click',
  'data-line-click',
  'data-surface-click'
]) // 定义自定义事件
const dialogVisible = ref(false)
window.CESIUM_BASE_URL = '/libs/cesium/' //'libs/cesium/'

let drawTool = null; // 绘制工具类实例
const longitude = ref(0);
const latitude = ref(0);
const height = ref(0);
onMounted(() => {
  Ion.defaultAccessToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiJmYjdlYjNjZi1kNDVhLTRhN2QtYjUzZi1lNDY4ZGE1NzFhODEiLCJpZCI6ODE3MzcsImlhdCI6MTY0NDI4MjczN30.cHW3lqt-x5liOSI_Q1Uvs6zYTZRRjliBI7ypZf2w90k";
  viewer = new Viewer(viewerDivRef.value, {
    geocoder: false,
    homeButton: false,
    sceneModePicker: false,
    baseLayerPicker: false,
    navigationHelpButton: false,
    animation: false,
    timeline: false,
    fullscreenButton: false,
    vrButton: false,
    selectionIndicator: false,
    infoBox: false,
    shouldAnimate: true,
    sceneMode: SceneMode.SCENE2D,
    terrain: Terrain.fromWorldTerrain(),
  })

  let options = {};
  // 用于在使用重置导航重置地图视图时设置默认视图控制。接受的值是Cesium.Cartographic 和 Cesium.Rectangle.
  options.defaultResetView = Rectangle.fromDegrees(80, 22, 130, 50);
  // 用于启用或禁用罗盘。true是启用罗盘，false是禁用罗盘。默认值为true。如果将选项设置为false，则罗盘将不会添加到地图中。
  options.enableCompass = false;
  // 用于启用或禁用缩放控件。true是启用，false是禁用。默认值为true。如果将选项设置为false，则缩放控件将不会添加到地图中。
  options.enableZoomControls = false;
  // 用于启用或禁用距离图例。true是启用，false是禁用。默认值为true。如果将选项设置为false，距离图例将不会添加到地图中。
  options.enableDistanceLegend = props.showDistanceLegend;
  // 用于启用或禁用指南针外环。true是启用，false是禁用。默认值为true。如果将选项设置为false，则该环将可见但无效。
  options.enableCompassOuterRing = false;
  new CesiumNavigation(viewer, options)

  const navigationMode = document.getElementsByClassName('distance-legend')[0]
  if (navigationMode) {
    navigationMode.style.bottom = '50px';
    navigationMode.style.left = '150px';
    navigationMode.style.zIndex = '999';
  }


  const tdtUrl = 'https://t{s}.tianditu.gov.cn/'
  const subdomains = ['0', '1', '2', '3', '4', '5', '6', '7']
  const token = 'ae371cfd360495022cfe9b37ed2b75a6';

  viewer._cesiumWidget._creditContainer.style.display = "none"; //去除右下角版权log
  viewer.imageryLayers.remove(viewer.imageryLayers.get(0)); // 默认的Cesium会加载一个bingMap底图，这个地图网络不太好，一般要先去掉这个默认的

  // 叠加影像服务
  var tdtImageryProvider = new UrlTemplateImageryProvider({
    url: tdtUrl + 'DataServer?T=img_w&x={x}&y={y}&l={z}&tk=' + token,
    subdomains: subdomains,
    tilingScheme: new WebMercatorTilingScheme(),
    maximumLevel: 18,
  })
  viewer.imageryLayers.addImageryProvider(tdtImageryProvider)

  // 叠加国界服务
  var iboMap = new UrlTemplateImageryProvider({
    url: tdtUrl + 'DataServer?T=ibo_w&x={x}&y={y}&l={z}&tk=' + token,
    subdomains: subdomains,
    tilingScheme: new WebMercatorTilingScheme(),
    maximumLevel: 10
  });
  viewer.imageryLayers.addImageryProvider(iboMap);

  var labelMap = new UrlTemplateImageryProvider({
    url: tdtUrl + "cia_w/wmts?tk=" + token + "&layer=cia&style=default&tilematrixset=w&Service=WMTS&Request=GetTile&Version=1.0.0&Format=tiles&TileMatrix={z}&TileCol={x}&TileRow={y}",
    subdomains: subdomains,
    tilingScheme: new WebMercatorTilingScheme(),
    maximumLevel: 18
  });
  viewer.imageryLayers.addImageryProvider(labelMap);

  viewer._cesiumWidget._creditContainer.style.display = "none";   //去除右下角版权log

  //Camera.DEFAULT_VIEW_RECTANGLE = Rectangle.fromDegrees(80, 22, 130, 50);

  useMapStore().setMap(viewer);

  viewer.camera.setView({
    // 从以度为单位的经度和纬度值返回笛卡尔3位置。
    destination: Cartesian3.fromDegrees(120.24182798488077, 35.99190621776263, 40000),
  });

  const handler = new ScreenSpaceEventHandler(viewer.scene.canvas);

  mapReady.value = true;

  drawTool = new CesiumDrawTool(viewer, emit); // 初始化工具类实例
  //左键单击点线面事件监听
  drawTool.on('data-point-click', handleDataPointClick);
  drawTool.on('data-line-click', handleDataLineClick);
  drawTool.on('data-surface-click', handleDataSurfaceClick);

  // 添加事件监听（使用setTimeout确保DOM完全加载）
  setTimeout(() => {
    const handleDrawPoint = (coords) => {
      taskForm.points = [coords];
    };
    const handleDrawLine = ({ points, totalLength }) => {
      taskForm.points = points;
      taskForm.length = totalLength.toFixed(2);
    };
    const handleDrawSurface = ({ points, area }) => {
      taskForm.points = points;
      taskForm.area = area.toFixed(2);
    };
    drawTool.on('draw-point', handleDrawPoint);
    drawTool.on('draw-line', handleDrawLine);
    drawTool.on('draw-surface', handleDrawSurface);
  }, 100);

  handler.setInputAction((movement) => {
    const cartesian = viewer.scene.camera.pickEllipsoid(
      movement.endPosition,
      viewer.scene.globe.ellipsoid
    );

    if (cartesian) {
      const cartographic = Cartographic.fromCartesian(cartesian);
      longitude.value = CesiumMath.toDegrees(cartographic.longitude).toFixed(6);
      latitude.value = CesiumMath.toDegrees(cartographic.latitude).toFixed(6);
    }
  }, ScreenSpaceEventType.MOUSE_MOVE);

  drawTool.on('entity-delete', handleEntityDelete);

})

// 绘制多边形
const drawPolygon = () => {
  drawTool.drawPolygon();
};

// 清除多边形
const clearPolygon = () => {
  drawTool.clearPolygon();
};

// 绘制环形
const drawCircle = () => {
  drawTool.drawCircle();
};

// 清除环形
const clearCircle = () => {
  // debugger
  drawTool.clearCircle();
  viewer.entities.remove(bj.value)
};

// 清除绘制状态
const resetDrawingState = () => {
  drawTool.resetDrawingState();
};

// 根据经纬度画多边形
const drawExistingPolygon = (points) => {
  return drawTool.drawExistingPolygon(points);
};

const bj = ref()

const pt =ref()

// 根据经纬度和半径画圆(用于机场)
const drawExistingCircle = (longitude, latitude, radius) => {
  bj.value = drawTool.drawExistingCircle(longitude, latitude, radius);
  return bj.value
};

const updateCircleRadius = (circleEntity, newRadius) => {
  circleEntity = bj.value
  if (circleEntity && circleEntity.ellipse) {
    circleEntity.ellipse.semiMajorAxis = newRadius;
    circleEntity.ellipse.semiMinorAxis = newRadius;
  }
};

// 根据经纬度和半径画圆(用于环形禁飞区)
const drawExistingCircleJFQ = (longitude, latitude, radius) => {
  return drawTool.drawExistingCircleJFQ(longitude, latitude, radius);
};

// 针对环形区域的跳转
const flyToCircle = (center, radius) => {
  drawTool.flyToCircle(center, radius);
};

// 针对多边形区域的跳转
const flyToPolygon = (center) => {
  drawTool.flyToPolygon(center);
};

const getViewer = () => {
  return drawTool.getViewer();
};

// 加载默认民航禁飞区
const loadDefaultNoFlyZones = (data) => {
  return drawTool.loadDefaultNoFlyZones(data);
};
//清除民航禁飞区
const clearDefaultNoFlyZones = (data) => {
  return drawTool.clearDefaultNoFlyZones(data);
};

//绘制点任务
const drawPoint = (pointData) => {
  return drawTool.drawPointFromData(pointData);
};

const drawgPointImg = (pointData) => {
  pt.value = drawTool.drawgPointImg(pointData);
  return pt.value
};


const clearPointImg = () => {
  viewer.entities.remove(pt.value)
};

const drawgPointDroneStation = (pointData) => {
  return drawTool.drawgPointDroneStation(pointData);
}

const addCircleWaveEffect = () => {
  return drawTool.addCircleWaveEffect(120.151837, 35.971190, {
    color: '#FFCB33',      // 颜色
    duration: 3000,        // 持续时间（毫秒）
    gradient: 0,           // 渐变曲率
    count: 4,             // 波浪数量
    radius: 7000,         // 半径（米）
    height: 50           // 高度（米）
  });
}

const removeAllCircleWaveEffects = () => {
  return drawTool.removeAllCircleWaveEffects();
}

const clearDroneStation = (entityOrId) => {
  return drawTool.clearDroneStation(entityOrId);
}

const setDefaultDroneImg = (entity) => {
  defaultDroneImg.value = entity;
}

const setDefaultStation = (entity) => {
  defaultStationCircle.value = entity;
};


const drawgDroneModel = (point) => {
  return drawTool.drawgDroneModel(point);
};

const updateDronePosition = (droneEntity, point) => {
  return drawTool.updateDronePosition(droneEntity, point);
};

//绘制线任务
const drawLine = (lineData) => {
  return drawTool.drawLineFromData(lineData);
};
//绘制面任务
const drawSurface = (surfaceData) => {
  return drawTool.drawSurfaceFromData(surfaceData);
};
//控制标签显示与隐藏按钮
const showName = () => {
  showName.isVisible = !showName.isVisible;
  drawTool.toggleLabelsVisibility(showName.isVisible);
};
//控制图形显示与隐藏按钮
const showGraphic = () => {
  showGraphic.isVisible = !showGraphic.isVisible;
  drawTool.toggleAllVisibility(showGraphic.isVisible);
};
//定位图标
const drawLocationMarker = (longitude, latitude) => {
  return drawTool.drawLocationMarker(longitude, latitude);
};
// 初始化标签状态变量
showName.isVisible = true;
//初始化图形状态变量
showGraphic.isVisible = true;


/** 首页图标状态和函数*/
const currentTaskType = ref('')
const showTaskForm = ref(false)
const taskForm = reactive({
  name: '',
  color: '#FF0000',
  length: 0,
  area: 0,
  points: []
})
const colors = ref(['#FF0000', '#00FF00', '#0000FF', '#FFFF00', '#FF00FF'])
// 在handleIconClick方法中设置颜色
const handleIconClick = (type) => {
  currentTaskType.value = type;
  showTaskForm.value = true;
  resetDrawing();

  // 如果是从编辑模式切换过来，重置颜色为默认值
  if (isEditMode.value) {
    taskForm.color = '#FF0000';
    isEditMode.value = false;
  }


  // 设置绘制工具的颜色
  drawTool.setActiveColor(taskForm.color);

  // 根据类型调用不同的绘制方法
  switch (type) {
    case 'point':
      drawTool.drawPoint();
      break;
    case 'line':
      drawTool.drawLine();
      break;
    case 'surface':
      drawTool.drawSurface();
      break;
  }
};
//点任务参数构造
const confirmPointTask = async () => {
  const params = {
    pointName: taskForm.name,
    pointColor: taskForm.color,
    dLongitude: taskForm.points[0].longitude, // 注意是Double类型
    dLatitude: taskForm.points[0].latitude    // 注意是Double类型
  };
  console.log('点任务参数:', params);
  await addPointTask(params);
};
//线任务参数构造
const confirmLineTask = async () => {
  const params = {
    lineName: taskForm.name,
    lineColor: taskForm.color,
    lineLength: parseFloat(taskForm.length), // 转为Double
    points: taskForm.points.map((p, index) => ({
      xLongitude: p.longitude.toString(),  // 注意是String
      xLatitude: p.latitude.toString(),    // 注意是String
      xOrder: index + 1                   // 从1开始
    }))
  };
  console.log('线任务参数:', JSON.stringify(params, null, 2));
  await addLineTask(params);
};
//面任务参数构造
const confirmSurfaceTask = async () => {
  const params = {
    surfaceName: taskForm.name,
    surfaceColor: taskForm.color,
    surfaceArea: taskForm.area.toString(), // 注意是String
    points: taskForm.points.map((p, index) => ({
      mLongitude: p.longitude.toString(),  // 注意是String
      mLatitude: p.latitude.toString(),    // 注意是String
      mOrder: index + 1                   // 从1开始
    }))
  };
  await addSurfaceTask(params);
};
//统一确定按钮
const confirmTask = async () => {
  try {
    // 公共验证
    if (!taskForm.name) throw new Error('请填写任务名称');
    if (taskForm.points.length === 0) throw new Error('请先绘制图形');
    // 设置最终颜色
    drawTool.setActiveColor(taskForm.color);
    // 根据类型调用不同方法
    switch (currentTaskType.value) {
      case 'point':
        await confirmPointTask();
        break;
      case 'line':
        await confirmLineTask();
        break;
      case 'surface':
        await confirmSurfaceTask();
        break;
    }
    //清除第一次数据绘制的图形
    drawTool.clearDataEntities();
    // 调用父组件的刷新方法
    emit('refresh');
    ElMessage.success('任务创建成功');
    cancelTask();
  } catch (error) {
    console.error('提交失败:', error);
    ElMessage.error(error.message);
  }
};
// 添加颜色变更处理方法
const handleColorChange = (color) => {
  taskForm.color = color;
  drawTool.setActiveColor(color);
  // 实时更新当前绘制实体的颜色
  switch (currentTaskType.value) {
    case 'point':
      drawTool.updateManualPointColor(color);
      break;
    case 'line':
      drawTool.updateManualLineColor(color);
      break;
    case 'surface':
      drawTool.updateManualSurfaceColor(color);
      break;
  }
};
// 重置任务参数
const resetDrawing = () => {
  Object.assign(taskForm, {
    name: '',
    color: '#FF0000',
    length: 0,
    area: 0,
    points: []
  })
}

// 接收 id 数组的方法
const receiveIds = async () => {
  try {
    const ids = await props.getAllIds();
    pointIds.value = ids.pointIds;
    lineIds.value = ids.lineIds;
    surfaceIds.value = ids.surfaceIds;
  } catch (error) {
    pointIds.value = [];
    lineIds.value = [];
    surfaceIds.value = [];
  }
};
const pointIds = ref([]);
const lineIds = ref([]);
const surfaceIds = ref([]);
// 删除所有任务
const deleteAllTasks = async () => {
  try {
    await ElMessageBox.confirm(
      '是否删除所有任务？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );
    await receiveIds(); // 等待 receiveIds 方法执行完成
    // 封装请求数据
    const requestData = {
      pointIds: pointIds.value,
      lineIds: lineIds.value,
      surfaceIds: surfaceIds.value
    };
    console.log('请求数据:', requestData);
    await deleteAllTaskByIds(requestData);
    // 清除数据绘制的图形
    drawTool.clearDataEntities();
    emit('refresh');
    ElMessage.success('删除成功');
  } catch (error) {
    if (error === 'cancel') {
      return;
    }
    ElMessage.error('删除失败');
  }
};

// 删除实体处理
const handleEntityDelete = async ({ type, id }) => {
  try {
    // 显示确认对话框
    const confirmResult = await ElMessageBox.confirm('确定要删除此任务吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });

    // 提取纯数字ID
    const pureId = extractPureId(id);
    if (!pureId) {
      throw new Error('无法解析ID');
    }

    let result;
    switch (type) {
      case 'point':
        result = await deletePointTaskById(Number(pureId)); // 确保转换为数字
        break;
      case 'line':
        result = await deleteLineTaskById(Number(pureId)); // 确保转换为数字
        break;
      case 'surface':
        result = await deleteSurfaceTaskById(Number(pureId)); // 确保转换为数字
        break;
    }
    // 如果当前显示的是被删除实体的任务卡，则关闭它
    if (showTaskForm.value && isEditMode.value && currentTaskType.value === type) {
      cancelTask();
    }

    // 清除数据绘制的图形
    drawTool.clearDataEntities();
    emit('refresh');
    ElMessage.success('删除成功');
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败: ' + error.message);
    }
  }
};
// 添加ID提取方法
const extractPureId = (id) => {
  // 处理不同格式的ID
  if (id.includes('point_')) {
    return id.replace('point_', '');
  }
  if (id.includes('line_')) {
    return id.replace('line_', '');
  }
  if (id.includes('surface_')) {
    return id.replace('surface_', '').replace('_polygon', '');
  }
  if (id.includes('_label')) {
    return id.replace('_label', '');
  }
  return id;
};
// 在data部分添加isEditMode
const isEditMode = ref(false);
// 添加一个方法确保颜色值标准化
const normalizeColor = (color) => {
  // 如果颜色值是预设的，直接返回
  if (colors.value.includes(color)) return color;

  // 否则找到最接近的预设颜色
  return colors.value.find(c => c.toLowerCase() === color.toLowerCase()) || '#FF0000';
};
//单击点
const handleDataPointClick = async ({ id, entity }) => {
  console.log('点要素被点击 ID:', id, '实体对象:', entity);
  try {
    const { pointInfo } = await props.getAllTaskInfo();
    // 提取纯数字ID（去掉前缀）
    const pureId = id.replace('point_', '');
    const pointData = pointInfo.find(item => item.id === pureId);
    if (pointData) {
      isEditMode.value = true;
      currentTaskType.value = 'point';
      taskForm.name = pointData.name;
      taskForm.color = normalizeColor(pointData.color); // 标准化颜色值
      taskForm.length = 0;
      taskForm.area = 0;
      taskForm.points = [];
      showTaskForm.value = true;
    }
  } catch (error) {
    console.error('获取点任务信息失败:', error);
    ElMessage.error('获取点任务信息失败');
  }
};

//单击线
const handleDataLineClick = async ({ id, entity }) => {
  console.log('线要素被点击 ID:', id, '实体对象:', entity);
  try {
    const { lineInfo } = await props.getAllTaskInfo();
    const pureId = id.replace('line_', '');
    const lineData = lineInfo.find(item => item.id === pureId);
    if (lineData) {
      isEditMode.value = true;
      currentTaskType.value = 'line';
      taskForm.name = lineData.name;
      taskForm.color = normalizeColor(lineData.color); // 标准化颜色值
      taskForm.length = lineData.totalLength;
      taskForm.area = 0;
      taskForm.points = [];
      showTaskForm.value = true;
    }
  } catch (error) {
    console.error('获取线任务信息失败:', error);
    ElMessage.error('获取线任务信息失败');
  }
};

//单击面
const handleDataSurfaceClick = async ({ id, entity }) => {
  console.log('面要素被点击 ID:', id, '实体对象:', entity);
  try {
    const { surfaceInfo } = await props.getAllTaskInfo();
    const pureId = id.replace('surface_', '').replace('_polygon', '');
    const surfaceData = surfaceInfo.find(item => item.id === pureId);
    if (surfaceData) {
      isEditMode.value = true;
      currentTaskType.value = 'surface';
      taskForm.name = surfaceData.name;
      taskForm.color = normalizeColor(surfaceData.color); // 标准化颜色值
      taskForm.area = surfaceData.totalArea;
      taskForm.length = 0;
      taskForm.points = [];
      showTaskForm.value = true;
    }
  } catch (error) {
    console.error('获取面任务信息失败:', error);
    ElMessage.error('获取面任务信息失败');
  }
};

// 取消方法
const cancelTask = () => {
  try {
    showTaskForm.value = false;
    isEditMode.value = false;
    if (drawTool) {
      drawTool.clearManualDrawings();
    }
    drawTool.cleanupHandlers();
    currentTaskType.value = '';
    viewer.scene.screenSpaceCameraController.enableInputs = true;
  } catch (error) {
    console.error('取消绘制时出错:', error);
  }
}

// 以下代码保持不变
/**个性化页面操作*/
const props = defineProps({
  mapConfig: {
    type: Object,
  },
  rightIsShow: {
    type: Boolean
  },
  showtoolbox: {
    type: Boolean,
    default: true
  },
  showweather: {
    type: Boolean,
    default: true
  },
  showswitchbox: {
    type: Boolean,
    default: true
  },
  dockMan: {
    type: Boolean,
    default: true
  },
  showbottomBox: {
    type: Boolean,
    default: true
  },
  showDistanceLegend: {
    type: Boolean,
    default: true // 默认显示比例尺
  },
  getAllIds: {
    type: Function,
    required: true
  },
  getAllTaskInfo: {
    type: Function,
    required: true
  }
})

// 监听props变化，更新地图视图
watch(() => props.mapConfig, (newConfig) => {
  updateMapView(newConfig.pcLongitude, newConfig.pcLatitude, newConfig.pcLayer);
}, { deep: true })

const updateMapView = (longitude, latitude, layer) => {
  if (viewer) {
    const lon = Number(longitude);
    const lat = Number(latitude);
    const lay = Number(layer);
    const height = lay * 1000;
    viewer.camera.setView({
      destination: Cartesian3.fromDegrees(lon, lat, height),
    });
  }
}
//存储机场实体的引用
const droneStationEntity = ref(null);
const droneImg = ref(null);
const stationCircle = ref(null);
// 添加一个变量存储默认机场实体
const defaultDroneImg = ref(null);
// 添加新的响应式引用来存储默认机站圆圈
const defaultStationCircle = ref(null);
const setSceneMode = (Number) => {
  activeMode.value = Number;
  const cameraPosition = viewer.scene.camera.positionCartographic;
  const longitude = CesiumMath.toDegrees(cameraPosition.longitude);
  const latitude = CesiumMath.toDegrees(cameraPosition.latitude);
  const height = cameraPosition.height;

  // 先清除所有机场实体
  const clearAllDroneEntities = () => {
    // 清除3D机场
    if (droneStationEntity.value) {
      clearDroneStation(droneStationEntity.value);
      droneStationEntity.value = null;
    }
    // 清除2D机场
    if (droneImg.value) {
      viewer.entities.remove(droneImg.value);
      droneImg.value = null;
    }
    // 清除2D机站圆圈
    if (stationCircle.value) {
      viewer.entities.remove(stationCircle.value);
      stationCircle.value = null;
    }
    // 清除默认2D机场
    if (defaultDroneImg.value) {
      viewer.entities.remove(defaultDroneImg.value);
      defaultDroneImg.value = null;
    }
    // 清除2D机站圆圈
    if (defaultStationCircle.value) {
      viewer.entities.remove(defaultStationCircle.value);
      defaultStationCircle.value = null;
    }
  };

  // 先清除所有实体
  clearAllDroneEntities();

  // 然后根据模式创建新的实体
  if (Number === 1) {
    //viewer.scene.morphTo2D(0);
    viewer.scene.mode = 2
    droneImg.value = drawgPointImg({ lng: 120.151837, lat: 35.971190, alt: 50 });
    stationCircle.value = drawExistingCircle(120.151837, 35.971190, 7000);

    removeAllCircleWaveEffects();
  } else {
    //viewer.scene.morphTo3D(0);
    viewer.scene.mode = 3
    droneStationEntity.value = drawgPointDroneStation({ lng: 120.151837, lat: 35.971190, alt: 0 });

    //切换三模式后 监听相机变化事件
    viewer.camera.changed.addEventListener(() => {
      //更据相机高度判断3D模式下机场缩放比例
      if(droneStationEntity.value){
   drawTool.updateModelParameters(droneStationEntity.value);
      }
   
    });

    addCircleWaveEffect();
  }

  viewer.scene.camera.setView({
    destination: Cartesian3.fromDegrees(longitude, latitude, height),
  });
}

const handleMark = () => {
  dialogVisible.value = !dialogVisible.value
}

// 放大地图
const zoomIn = () => {
  if (viewer.scene.mode === SceneMode.SCENE2D) {
    const frustum = viewer.camera.frustum;
    const zoomFactor = 0.8;
    frustum.top *= zoomFactor;
    frustum.bottom *= zoomFactor;
    frustum.right *= zoomFactor;
    frustum.left *= zoomFactor;
  } else {
    const cartographic = Cartographic.fromCartesian(viewer.camera.position);
    const height = cartographic.height;
    viewer.camera.zoomIn(height / 3);
  }
}
// 缩小地图
const zoomOut = () => {
  if (viewer.scene.mode === SceneMode.SCENE2D) {
    const frustum = viewer.camera.frustum;
    const zoomFactor = 1.2;
    frustum.top *= zoomFactor;
    frustum.bottom *= zoomFactor;
    frustum.right *= zoomFactor;
    frustum.left *= zoomFactor;
  } else {
    const cartographic = Cartographic.fromCartesian(viewer.camera.position);
    const height = cartographic.height;
    viewer.camera.zoomOut(height / 3);
  }
}

/****************************************搜索框方法**********************/
const showSearch = ref(false)
const searchKeyword = ref('')
const toggleSearch = () => {
  showSearch.value = !showSearch.value
}
const querySearch = async (queryString, callback) => {
  if (queryString.length === 0) {
    callback([])
    return
  }
  try {
    const response = await fetch(`https://restapi.amap.com/v3/place/text?key=54a94cd0abeb4219067be1f3385406ca&keywords=${encodeURIComponent(queryString)}&city=全国&output=JSON&offset=10&page=1&extensions=base`)
    const data = await response.json()
    console.log(data)

    if (data.status === '1' && data.pois) {
      const results = data.pois.map(poi => ({
        value: poi.name,
        name: poi.name,
        district: poi.adname,
        location: poi.location
      }))
      callback(results)
    } else {
      callback([])
    }
  } catch (error) {
    console.error('搜索出错:', error)
    callback([])
  }
}
let isFirstCall = true;
let currentMarker;
const handleSelect = (item) => {
  const [longitude, latitude] = item.location.split(',').map(Number);
  // 如果不是第一次调用，先清除之前的图标
  if (!isFirstCall && currentMarker) {
    viewer.entities.remove(currentMarker);
  }
  viewer.camera.flyTo({
    destination: Cartesian3.fromDegrees(longitude, latitude, 10000),
    duration: 2
  });
  currentMarker = drawLocationMarker(longitude, latitude);
  // 标记为不是第一次调用
  isFirstCall = false;
  // 手动聚焦输入框
  nextTick(() => {
    searchKeyword.value = item.name;
    const input = document.querySelector('.search-input .el-input__inner');
    input?.focus();
  });
};
const resetSearch = () => {
  searchKeyword.value = '';
  showSearch.value = false;
  if (currentMarker) {
    viewer.entities.remove(currentMarker);
    currentMarker = null;
  }
  isFirstCall = true; // 重置为第一次调用
}

/********定位图标方法********/
const handleLocation = () => {
  viewer.camera.flyTo({
    destination: Cartesian3.fromDegrees(120.151837, 35.971190, 1000),
    duration: 2
  });
}

/********************************测距图标方法******************************/
let distanceTool = null; // 距离工具类实例
let areaTool = null; // 面积工具类实例
// 新增测量相关状态
const showMeasureBox = ref(false);
const isMeasureDistance = ref(false);
const isMeasureArea = ref(false);
let savedMeasureData = null; // 保存测距数据

// 修改测量图标点击处理
const handleMeasureDistance = () => {
  showMeasureBox.value = !showMeasureBox.value;
  if (!showMeasureBox.value) {
    savedMeasureData = distanceTool.getMeasureData(); // 保存测量数据
    distanceTool.deactivate();
    areaTool?.deactivate();
  } else {
    distanceTool.deactivate();
    areaTool?.deactivate();
  }
};

// 选择测量模式
const selectMeasureMode = (mode) => {
  if (mode === 'distance') {
    isMeasureDistance.value = true;
    isMeasureArea.value = false;
    // 激活测距工具
    if (!distanceTool) {
      distanceTool = new CesiumMeasureDistance(viewer);
      distanceTool.MeasureEndEvent.addEventListener((distance) => {
        ElMessage({ message: `测量距离：${distance.toFixed(2)} 米`, type: 'info' });
      });
    }
    distanceTool.activate();
  } else if (mode === 'area') {
    isMeasureDistance.value = false;
    isMeasureArea.value = true;
    // 停用测距工具并保存数据
    if (distanceTool) {
      savedMeasureData = {
        positions: distanceTool.positions,
        vertexEntities: distanceTool.vertexEntities,
        measureDistance: distanceTool.measureDistance
      };
      distanceTool.deactivate();
    }
    // 初始化测面积工具（如果未初始化）
    if (!areaTool) {
      areaTool = new CesiumMeasureArea(viewer);
      areaTool.MeasureEndEvent.addEventListener((area) => {
        ElMessage({
          message: `测量面积：${area.toFixed(2)} 平方米`,
          type: 'info'
        });
      });
    }
    areaTool.activate(); // 激活测面积工具
  }
};

/***********************************************图层图标系列方法及其变量***********************************************/
const showLayerSettings = ref(false)
const brightness = ref(0)
const currentMapType = ref('satellite')
const modelQuality = ref('high')
const flightRestrictionActive = ref(true);
const roadNetworkVisible = ref(true)
let isNoFlyZoneVisible = true;
let isSystemFlyZoneVisible = false;
const systemRestrictionVisible = ref(false)
//图层卡片显示与隐藏
const toggleLayerSettings = () => {
  showLayerSettings.value = !showLayerSettings.value
}
// 实现亮度调节
const handleBrightnessChange = (value) => {
  brightness.value = value;
  if (viewer && viewer.scene && viewer.scene.globe) {
    // 调整地球模型的亮度
    viewer.scene.globe.brightness = value / 50;
    // 调整场景的高动态范围和伽马校正
    viewer.scene.gammaCorrection = value / 100 + 0.5;
    // 调整影像图层的透明度
    const layers = viewer.imageryLayers._layers;
    layers.forEach((layer) => {
      if (layer) {
        layer.alpha = 1 + (value / 400);
      }
    });
    viewer.scene.requestRender();
  }
};

// 实现地图类型切换逻辑
const tdtUrl = 'https://t{s}.tianditu.gov.cn/'
const subdomains = ['0', '1', '2', '3', '4', '5', '6', '7']
const token = 'ae371cfd360495022cfe9b37ed2b75a6';
// 实现地图类型切换逻辑
const switchMapType = (type) => {
  currentMapType.value = type;

  // 移除所有图层
  viewer.imageryLayers.removeAll();

  if (type === 'normal') {
    // 切换到天地图普通
    const normalUrl = `https://t{s}.tianditu.gov.cn/DataServer?T=vec_w&x={x}&y={y}&l={z}&tk=${token}`;
    const tdtImageryProvider = new UrlTemplateImageryProvider({
      url: normalUrl,
      subdomains: subdomains,
      tilingScheme: new WebMercatorTilingScheme(),
      maximumLevel: 18,
    });
    viewer.imageryLayers.addImageryProvider(tdtImageryProvider);

    // 添加国界服务
    const iboMap = new UrlTemplateImageryProvider({
      url: tdtUrl + 'DataServer?T=ibo_w&x={x}&y={y}&l={z}&tk=' + token,
      subdomains: subdomains,
      tilingScheme: new WebMercatorTilingScheme(),
      maximumLevel: 10
    });
    viewer.imageryLayers.addImageryProvider(iboMap);

    // 如果路网可见，添加标注图层
    if (roadNetworkVisible.value) {
      const normalLabelMap = new UrlTemplateImageryProvider({
        url: tdtUrl + "cva_w/wmts?tk=" + token + "&layer=cva&style=default&tilematrixset=w&Service=WMTS&Request=GetTile&Version=1.0.0&Format=tiles&TileMatrix={z}&TileCol={x}&TileRow={y}",
        subdomains: subdomains,
        tilingScheme: new WebMercatorTilingScheme(),
        maximumLevel: 18
      });
      viewer.imageryLayers.addImageryProvider(normalLabelMap);
    }
  } else {
    // 切换到天地图卫星
    const satelliteUrl = `https://t{s}.tianditu.gov.cn/DataServer?T=img_w&x={x}&y={y}&l={z}&tk=${token}`;
    const tdtImageryProvider = new UrlTemplateImageryProvider({
      url: satelliteUrl,
      subdomains: subdomains,
      tilingScheme: new WebMercatorTilingScheme(),
      maximumLevel: 18,
    });
    viewer.imageryLayers.addImageryProvider(tdtImageryProvider);

    // 添加国界服务
    const iboMap = new UrlTemplateImageryProvider({
      url: tdtUrl + 'DataServer?T=ibo_w&x={x}&y={y}&l={z}&tk=' + token,
      subdomains: subdomains,
      tilingScheme: new WebMercatorTilingScheme(),
      maximumLevel: 10
    });
    viewer.imageryLayers.addImageryProvider(iboMap);

    // 如果路网可见，添加标注图层
    if (roadNetworkVisible.value) {
      const labelMap = new UrlTemplateImageryProvider({
        url: tdtUrl + "cia_w/wmts?tk=" + token + "&layer=cia&style=default&tilematrixset=w&Service=WMTS&Request=GetTile&Version=1.0.0&Format=tiles&TileMatrix={z}&TileCol={x}&TileRow={y}",
        subdomains: subdomains,
        tilingScheme: new WebMercatorTilingScheme(),
        maximumLevel: 18
      });
      viewer.imageryLayers.addImageryProvider(labelMap);
    }
  }
};
// 实现3D模型质量设置
const setModelQuality = (quality) => {
  modelQuality.value = quality;
  
  if (quality === 'high') {
    // 高质量设置
    viewer.scene.globe.enableLighting = true;
    viewer.scene.globe.baseColor = new Color(1.0, 1.0, 1.0, 1.0);
    viewer.scene.postProcessStages.fxaa.enabled = true; // 启用FXAA抗锯齿
    viewer.scene.fog.enabled = true; // 启用雾效果
    viewer.scene.fog.density = 0.0002; // 设置雾密度
    viewer.scene.globe.maximumScreenSpaceError = 1.0; // 降低误差值，提高细节
    viewer.shadows = true; // 启用阴影
    viewer.scene.globe.depthTestAgainstTerrain = true; // 启用地形深度测试
  } else {
    // 低质量设置（流畅模式）
    viewer.scene.globe.enableLighting = false;
    viewer.scene.globe.baseColor = new Color(0.8, 0.8, 0.8, 1.0);
    viewer.scene.postProcessStages.fxaa.enabled = false; // 禁用抗锯齿
    viewer.scene.fog.enabled = false; // 禁用雾效果
    viewer.scene.globe.maximumScreenSpaceError = 4.0; // 增加误差值，降低细节以提高性能
    viewer.shadows = false; // 禁用阴影
    viewer.scene.globe.depthTestAgainstTerrain = false; // 禁用地形深度测试
  }
  
  // 强制场景刷新
  viewer.scene.requestRender();
};
// 实现路网显示/隐藏
const toggleRoadNetwork = () => {
  roadNetworkVisible.value = !roadNetworkVisible.value;

  // 移除所有图层
  viewer.imageryLayers.removeAll();

  if (currentMapType.value === 'normal') {
    // 添加天地图普通底图
    const normalUrl = `https://t{s}.tianditu.gov.cn/DataServer?T=vec_w&x={x}&y={y}&l={z}&tk=${token}`;
    const tdtImageryProvider = new UrlTemplateImageryProvider({
      url: normalUrl,
      subdomains: subdomains,
      tilingScheme: new WebMercatorTilingScheme(),
      maximumLevel: 18,
    });
    viewer.imageryLayers.addImageryProvider(tdtImageryProvider);

    // 添加国界服务
    const iboMap = new UrlTemplateImageryProvider({
      url: tdtUrl + 'DataServer?T=ibo_w&x={x}&y={y}&l={z}&tk=' + token,
      subdomains: subdomains,
      tilingScheme: new WebMercatorTilingScheme(),
      maximumLevel: 10
    });
    viewer.imageryLayers.addImageryProvider(iboMap);

    // 如果路网可见，添加标注图层
    if (roadNetworkVisible.value) {
      const normalLabelMap = new UrlTemplateImageryProvider({
        url: tdtUrl + "cva_w/wmts?tk=" + token + "&layer=cva&style=default&tilematrixset=w&Service=WMTS&Request=GetTile&Version=1.0.0&Format=tiles&TileMatrix={z}&TileCol={x}&TileRow={y}",
        subdomains: subdomains,
        tilingScheme: new WebMercatorTilingScheme(),
        maximumLevel: 18
      });
      viewer.imageryLayers.addImageryProvider(normalLabelMap);
    }
  } else {
    // 添加天地图卫星底图
    const satelliteUrl = `https://t{s}.tianditu.gov.cn/DataServer?T=img_w&x={x}&y={y}&l={z}&tk=${token}`;
    const tdtImageryProvider = new UrlTemplateImageryProvider({
      url: satelliteUrl,
      subdomains: subdomains,
      tilingScheme: new WebMercatorTilingScheme(),
      maximumLevel: 18,
    });
    viewer.imageryLayers.addImageryProvider(tdtImageryProvider);

    // 添加国界服务
    const iboMap = new UrlTemplateImageryProvider({
      url: tdtUrl + 'DataServer?T=ibo_w&x={x}&y={y}&l={z}&tk=' + token,
      subdomains: subdomains,
      tilingScheme: new WebMercatorTilingScheme(),
      maximumLevel: 10
    });
    viewer.imageryLayers.addImageryProvider(iboMap);

    // 如果路网可见，添加标注图层
    if (roadNetworkVisible.value) {
      const labelMap = new UrlTemplateImageryProvider({
        url: tdtUrl + "cia_w/wmts?tk=" + token + "&layer=cia&style=default&tilematrixset=w&Service=WMTS&Request=GetTile&Version=1.0.0&Format=tiles&TileMatrix={z}&TileCol={x}&TileRow={y}",
        subdomains: subdomains,
        tilingScheme: new WebMercatorTilingScheme(),
        maximumLevel: 18
      });
      viewer.imageryLayers.addImageryProvider(labelMap);
    }
  }
}
// 实现民航禁飞区显示/隐藏
const toggleFlightRestriction = () => {
  flightRestrictionActive.value = !flightRestrictionActive.value;
  if (isNoFlyZoneVisible) {
    clearDefaultNoFlyZones();
  } else {
    loadDefaultNoFlyZones(defaultNoFlyZone);
  }
  isNoFlyZoneVisible = !isNoFlyZoneVisible;
}
// 实现系统禁飞区显示/隐藏
// 在组件中定义存储变量
const systemFlyZoneEntities = ref([]);
// 修改后的切换方法
const toggleSystemRestriction = async () => {
  systemRestrictionVisible.value = !systemRestrictionVisible.value;

  if (isSystemFlyZoneVisible) {
    // 清除所有系统禁飞区实体
    systemFlyZoneEntities.value.forEach(entity => {
      viewer.entities.remove(entity);
    });
    systemFlyZoneEntities.value = [];
  } else {
    // 加载系统禁飞区
    const [hxResponse, dbxResponse] = await Promise.all([
      getHxUnflyZoneList(),
      getDbxUnflyZoneList()
    ]);

    // 绘制圆形禁飞区
    const circleEntities = hxResponse.rows.map(item => {
      const entities = drawExistingCircleJFQ(item.hxLongitude, item.hxLatitude, item.hxRadius);
      return entities[0]; // 返回第一个实体
    });

    // 绘制多边形禁飞区
    const polygonEntities = dbxResponse.rows.map(item => {
      const points = item.points.map(p => [p.pointLongitude, p.pointLatitude]);
      const entities = drawExistingPolygon(points);
      return entities[0]; // 返回第一个实体
    });

    // 保存所有实体
    systemFlyZoneEntities.value = [...circleEntities, ...polygonEntities];
  }

  isSystemFlyZoneVisible = !isSystemFlyZoneVisible;
}

// 轨迹动画相关状态
const animationState = ref({
  entity: null,  // 无人机实体
  isPlaying: false,
  startTime: null,
  stopTime: null,
  speed: 1
});

// 轨迹动画处理方法
const loadDroneTrack = (trackPoints) => {
  // 1. 数据预处理
  const positions = trackPoints.map(point => ({
    longitude: point.lng,
    latitude: point.lat,
    height: point.elevation || 100
  }));
  const heading = new SampledProperty(Number)

  // 2. 设置时间线
  const startTime = JulianDate.fromDate(new Date(trackPoints[0].time));
  const stopTime = JulianDate.fromDate(new Date(trackPoints[trackPoints.length - 1].time));

  viewer.clock.startTime = startTime.clone();
  viewer.clock.stopTime = stopTime.clone();
  viewer.clock.currentTime = startTime.clone();
  viewer.clock.clockRange = ClockRange.LOOP_STOP;
  viewer.clock.multiplier = animationState.value.speed;

  // 3. 计算轨迹插值
  const position = new SampledPositionProperty();
  positions.forEach((pos, index) => {
    const time = JulianDate.fromDate(new Date(trackPoints[index].time));
    position.addSample(
      time,
      Cartesian3.fromDegrees(pos.longitude, pos.latitude, pos.height)
    );
  });

  // 4. 创建无人机实体
  const entity = viewer.entities.add({
    availability: new TimeIntervalCollection([new TimeInterval({
      start: startTime,
      stop: stopTime
    })]),
    position: position,
    orientation: new CallbackProperty((time) => {
      const headingValue = heading.getValue(time);
      return Transforms.headingPitchRollQuaternion(
        position.getValue(time),
        new HeadingPitchRoll(headingValue, 0, 0)
      );
    }, false),
    model: {
      uri: CesiumDrone, // 无人机模型
      minimumPixelSize: 64,
      maximumScale: 200,
      scale: 0.5
    },
    path: {
      resolution: 1,
      material: new PolylineGlowMaterialProperty({
        glowPower: 0.1,
        color: Color.YELLOW
      }),
      width: 5
    }
  });

  // 5. 更新状态
  animationState.value = {
    ...animationState.value,
    entity,
    startTime,
    stopTime
  };

  // 6. 相机跟随
  //viewer.trackedEntity = entity;

  return entity;
};

// 播放控制
const playTrack = () => {
  viewer.clock.shouldAnimate = true;
  animationState.value.isPlaying = true;
};

const pauseTrack = () => {
  viewer.clock.shouldAnimate = false;
  animationState.value.isPlaying = false;
};

const stopTrack = () => {
  pauseTrack();
  if (viewer.clock) {
    viewer.clock.currentTime = animationState.value.startTime?.clone();
  }
};

const setTrackSpeed = (speed) => {
  animationState.value.speed = speed;
  if (viewer.clock) {
    viewer.clock.multiplier = speed;
  }
};

const clearTrack = () => {
  if (animationState.value.entity) {
    viewer.entities.remove(animationState.value.entity);
    animationState.value.entity = null;
  }
  viewer.trackedEntity = undefined;
};

defineExpose({
  drawPolygon,
  clearPolygon,
  drawCircle,
  clearCircle,
  resetDrawingState,
  drawExistingCircle,
  updateCircleRadius,
  drawExistingCircleJFQ,
  drawExistingPolygon,
  getViewer,
  flyToCircle,
  flyToPolygon,
  loadDefaultNoFlyZones,
  drawPoint,
  drawgPointImg,
  drawgDroneModel,
  updateDronePosition,
  drawLine,
  drawSurface,
  drawLocationMarker,
  setDefaultDroneImg,
  setDefaultStation,
  loadDroneTrack,
  playTrack,
  pauseTrack,
  stopTrack,
  setTrackSpeed,
  clearTrack,
  clearPointImg
});
</script>

<style scoped lang="scss">
#cesiumContainer {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  width: 100%;
  height: 100%;
}

/* 添加天气组件包装器样式 */
.weather-wrapper {
  position: absolute;
  top: 0px;
  left: 0px;
  z-index: 1000;
  pointer-events: auto;
  background: rgba(255, 255, 255, 0);
}

.markBox {
  display: flex;
  align-items: center;
  justify-content: space-around;
  color: #fff;
  width: 300px;
  height: 64px;
  position: absolute;
  z-index: 998;
  background: #1a1a1a;
  border-radius: 1px;
  border: 1px solid rgba(255, 255, 255, .3);
  box-shadow: 0 0 10px #000, inset 0 0 10px #6d7cc733;
  top: 99px;
}

.svg-icon {
  height: 26px;
  width: 26px;
}

.bottomBox {
  background: rgba(0, 0, 0, .86);
  color: #fff;
  font-size: 12px;
  height: 33px;
  width: 270px;
  bottom: 40px;
  left: 0px;
  position: absolute;
  display: flex;
  z-index: 101;
}

.switchBox {
  position: absolute;
  width: 32px;
  height: 64px;
  border-radius: 2px;
  opacity: 1;
  background: rgba(26, 26, 26, .95);
  box-shadow: 0 2px 3px #8d8d9030;
  display: flex;
  flex-direction: column;
  top: calc(50% - 32px);
  z-index: 100;

  .switchDiv {
    width: 32px;
    height: 32px;
    font-family: Microsoft Sans Serif;
    font-size: 14px;
    font-weight: 400;
    color: #dbdde2;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    border-radius: 2px 2px 0 0;
  }

  .isActive {
    background-color: #1177FB;
  }
}

.toolBox {
  height: 302px;
  width: 80px;
  bottom: 24px;
  position: absolute;
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  z-index: 101;

  .toolbarDiv {
    margin-top: 4px;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 32px;
    height: 32px;
    border-radius: 2px;
    background: rgba(9, 12, 21, .5);
    box-shadow: 0 2px 3px #8d8d9030;
    cursor: pointer;
  }

  .toolbarPm {
    margin-top: 3px;
    width: 32px;
    border-radius: 2px;
    overflow: hidden;
    box-shadow: 0 2px 3px #8d8d9030;
    display: flex;
    background: rgba(9, 12, 21, .5);
    flex-direction: column;
    justify-content: center;
    align-items: center;

    .line {
      width: 19px;
      height: 1px;
      background: rgba(255, 255, 255, .1);
    }

    .toolbarDiv {
      margin-top: 0;
      border-radius: 0;
      box-shadow: unset;
      background: transparent;
    }
  }

  a {
    color: #fff;
  }

  .toolLayer {
    margin-top: 10px !important;
    width: 80px !important;
    height: 80px !important;

    .LayerBox {
      position: relative;
      width: 68px;
      height: 68px;
      border-radius: 1px;
      background-size: 100% 100%;
      background-image: url("../../assets/images/imageClass.png");

      .LayerWrapper {
        position: absolute;
        bottom: 0;
        display: flex;
        align-items: flex-end;
        justify-content: center;
        width: 100%;
        height: 30px;
        font-size: 12px;
        border-radius: 0 0 2px 2px;
        background: linear-gradient(180deg, rgba(0, 0, 0, 0) 0%, rgba(0, 0, 0, .68) 100%);
      }
    }
  }

  :deep(.distance-legend) {
    bottom: 300px !important;
  }
}

/* 新增表单样式 */
.taskForm {
  position: absolute;
  top: 180px;
  width: 300px;
  background: #1a1a1a;
  padding: 15px;
  border-radius: 4px;
  z-index: 999;
  border: 1px solid rgba(255, 255, 255, .3);
  box-shadow: 0 0 10px #000, inset 0 0 10px #6d7cc733;

  .formHeader {
    color: #fff;
    font-size: 16px;
    margin-bottom: 15px;
    text-align: center;
  }

  .formItem {
    margin-bottom: 15px;

    label {
      color: #fff;
      display: block;
      margin-bottom: 5px;
      font-size: 14px;
    }
  }

  .colorPicker {
    display: flex;
    gap: 10px;
    margin-top: 8px;

    div {
      width: 25px;
      height: 25px;
      border-radius: 50%;
      cursor: pointer;
      border: 2px solid transparent;
      transition: all 0.3s;

      &:hover {
        transform: scale(1.1);
      }

      &.selected {
        border-color: #fff;
        transform: scale(1.1);
      }
    }
  }

  .formFooter {
    margin-top: 20px;
    text-align: right;

    .el-button {
      margin-left: 10px;
    }
  }
}

.colorPicker div.selected {
  border: 2px solid white;
  box-shadow: 0 0 5px rgba(255, 255, 255, 0.8);
  transform: scale(1.1);
}

.colorDisplay {
  width: 25px;
  height: 25px;
  border-radius: 50%;
  display: inline-block;
  border: 1px solid #ccc;
}

.search-container {
  position: absolute;
  left: -300px;
  top: 0;
  z-index: 1000;
}

.search-input {
  width: 280px;
}

.search-suggestion-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 5px 0;

  .district {
    color: #999;
    font-size: 12px;
  }
}

:deep(.el-input__wrapper) {
  background-color: black;
}

/* 新增测量模式选择框样式 */
.measureModeBox {
  position: absolute;
  left: 0;
  top: 100px;
  width: 80px;
  height: 60px;
  background: rgba(26, 26, 26, 0.95);
  border-radius: 4px 4px 0 0;
  overflow: hidden;
  transition: left 0.3s ease;
  z-index: 1000;

  .modeItem {
    height: 30px;
    line-height: 30px;
    text-align: center;
    color: #dbdde2;
    cursor: pointer;
    border-bottom: 1px solid rgba(255, 255, 255, 0.1);

    &.active {
      background: #1177FB;
      color: white;
    }
  }
}

.layerSettings {
  position: absolute;
  bottom: 150px;
  width: 300px;
  background: #1a1a1a;
  padding: 15px;
  border-radius: 4px;
  z-index: 999;
  border: 1px solid rgba(255, 255, 255, .3);
  box-shadow: 0 0 10px #000, inset 0 0 10px #6d7cc733;

  .settingsHeader {
    color: #fff;
    font-size: 16px;
    text-align: center;
    margin-bottom: 10px;
  }

  .settingsSection {
    margin-bottom: 20px;

    .sectionTitle {
      color: #fff;
      font-size: 14px;
      margin-bottom: 10px;
    }
  }

  .mapTypeContainer {
    display: flex;
    justify-content: space-between;
    gap: 10px;

    .mapTypeBox {
      width: 120px;
      height: 80px;
      cursor: pointer;
      position: relative;
      border-radius: 4px;
      overflow: hidden;
      border: 2px solid transparent;
      transition: all 0.3s;

      &.active {
        border-color: #1177FB;
      }

      .mapTypeImage {
        width: 100%;
        height: 100%;
        background-size: cover;
        background-position: center;

        &.normal {
          background-image: url("../../assets/images/normalMap.png");
        }

        &.satellite {
          background-image: url("../../assets/images/satelliteMap.png");
        }
      }

      .mapTypeLabel {
        position: absolute;
        bottom: 0;
        left: 0;
        right: 0;
        padding: 5px;
        background: rgba(0, 0, 0, 0.7);
        color: #fff;
        font-size: 12px;
        text-align: center;
      }
    }
  }

  .modelSettings {
    display: flex;
    gap: 10px;

    .modelOption {
      flex: 1;
      height: 32px;
      line-height: 32px;
      text-align: center;
      background: rgba(255, 255, 255, 0.1);
      color: #fff;
      cursor: pointer;
      border-radius: 4px;
      transition: all 0.3s;

      &.active {
        background: #1177FB;
      }
    }
  }

  .overlayContainer {
    display: flex;
    justify-content: space-between;
    gap: 10px;

    .overlayBox {
      width: 80px;
      height: 80px;
      cursor: pointer;
      position: relative;
      border-radius: 4px;
      overflow: hidden;
      border: 2px solid transparent;
      transition: all 0.3s;

      &.active {
        border-color: #1177FB;
        box-shadow: 0 0 8px rgba(17, 119, 251, 0.5);
      }

      .overlayImage {
        width: 100%;
        height: 100%;
        background-size: cover;
        background-position: center;

        &.road {
          background-image: url("../../assets/images/roadNetwork.png");
        }

        &.flight {
          background-image: url("../../assets/images/flightRestriction.png");
        }

        &.system {
          background-image: url("../../assets/images/systemRestriction.png");
        }
      }

      .overlayLabel {
        position: absolute;
        bottom: 0;
        left: 0;
        right: 0;
        padding: 5px;
        background: rgba(0, 0, 0, 0.7);
        color: #fff;
        font-size: 12px;
        text-align: center;
      }
    }
  }
}

:deep(.el-slider__runway) {
  background-color: rgba(255, 255, 255, 0.1);
}

:deep(.el-slider__bar) {
  background-color: #1177FB;
}

:deep(.el-slider__button) {
  border-color: #1177FB;
}
</style>
